import java.util.Stack;

/**
 * 字符串解码
 * https://leetcode-cn.com/problems/decode-string/
 * @author junzhongliu
 * @date 2018/12/25 13:20
 */
public class DecodeString {

    public static void main(String[] args) {
        String s = "3[a2[c]]";
        System.out.println(decodeString(s));
    }

    public static String decodeString(String s){
        //用于存储“[”前数字栈的字符串
        Stack<Integer> intStack = new Stack<>();
        //用于存储待复制多个操作的字符串
        Stack<String> strStack = new Stack<>();
        char[] chars = s.toCharArray();
        StringBuffer sb = new StringBuffer();
        //用于临时计数
        int tmpCount=0;
        for(Character c : chars){
            if(Character.isDigit(c)){
                //字符是数字
                tmpCount = tmpCount * 10 + c - '0';
            }else if(c=='['){
                //左括号，将计数的入栈
                intStack.push(tmpCount);
                tmpCount=0;
                strStack.push(sb.toString());
                sb = new StringBuffer();
            }else if(c ==']'){
                //右括号，出栈
                String tempStr = sb.toString();
                Integer pop = intStack.pop();
                //最核心的代码，每次遍历之前，先把原来栈中的字符弹出，追加到最前面
                sb = new StringBuffer(strStack.pop());
                for(int i=pop;pop>0;pop--){
                    sb.append(tempStr);
                }
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }

}
